package cn.wolfcode.web.controller;

import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CommonCodeMsg;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.DateUtil;
import cn.wolfcode.util.UserUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderInfoController {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;
    public static ConcurrentMap<Long,Boolean> map = new ConcurrentHashMap<>();

    @RequestMapping("/doSeckill")
    @RequireLogin
    public Result<String> doSeckill(HttpServletRequest request, Integer time, Long seckillId) {
        //判断参数校验
        if (StringUtils.isEmpty(time + "") || StringUtils.isEmpty(seckillId + "")) {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        //判断本地标识
        Boolean flag = map.get(seckillId);
        if (flag != null && flag){
         throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        SeckillProductVo vo = seckillProductService.find(seckillId, time);
        //判断是否在活动时间内
        /*boolean flag = DateUtil.isLegalTime(vo.getStartDate(), time);
        if (!flag) {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }*/
        //判断库存是否充足
        if (vo.getStockCount() < 0) {
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }

        //减少redis缓存（预存库）
        Long count = redisTemplate.opsForHash().increment(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time + ""), seckillId + "", -1);
        if (count < 0){
            //redis预存已经减到负数，说明放行的人已经足够了
            map.put(seckillId,true);
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }

        //判断是否重复下单
        String token = request.getHeader("token");
        UserInfo user = UserUtil.getUser(redisTemplate,token);
        Boolean isFlag = redisTemplate.opsForSet().isMember(SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(time + ""), user.getPhone() + ":" + seckillId);
        if (isFlag){
            throw new BusinessException(SeckillCodeMsg.REPEAT_SECKILL);
        }
        //执行秒杀订单业务
        //String orderInfo = orderInfoService.doSeckill(time,seckillId,user.getPhone());
        //把数据封装成消息发送到MQ中
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setSeckillId(seckillId);
        orderMessage.setTime(time);
        orderMessage.setToken(token);
        orderMessage.setUserPhone(user.getPhone());
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_PEDDING_TOPIC,orderMessage);
        return Result.success("正在抢购中，请稍后再试");
    }

    @RequestMapping("/find")
    public Result<OrderInfo> find(HttpServletRequest request,String orderNo){
        if (StringUtils.isEmpty(orderNo)){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        if (orderInfo == null){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        //当前登录用户只能看到自己的订单详情
        UserInfo userInfo = UserUtil.getUser(redisTemplate, request.getHeader("token"));
        if (!userInfo.getPhone().equals(orderInfo.getUserId())){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        return Result.success(orderInfo);
    }
}
